<template>
  <el-row style="justify-content: center;align-items:center;height: 5vh;padding-left: 2%;padding-right: 3%">
    <el-col :span="24">
      <el-radio-group v-model="radio" size="large" @click="updateRadio">
        <el-radio-button label="活动列表"/>
        <el-radio-button label="新活动"/>
      </el-radio-group>
    </el-col>
  </el-row>
  <el-row
      style="justify-content: center;align-items:center;height: 5vh;padding-left: 2%;padding-right: 3%;margin-bottom: 1%">
    <el-col :span="24" style="text-align: right;">
      <el-button v-if="radio==='新活动'" size="large" type="warning" style="margin-right: 1%"
                 @click="showNewActivity({code:'global'})">新建全局活动
      </el-button>
      <el-text size="large" v-if="radio==='活动列表'" style="margin-right: 1%">只显示进行中活动
        <el-switch size="large" v-model="isRunning" @click="runOrAll" style="margin-left: 1%"/>
      </el-text>
      <el-select v-if="radio==='新活动'" v-model="curType" placeholder="选择类别" size="large" @change="handleSelect"
                 style="width: 20%;margin-right: 1%">
        <el-option
            v-for="item in typeList"
            :key="item"
            :label="item"
            :value="item"
        />
      </el-select>
      <el-input
          v-if="radio==='新活动'"
          v-model="searchValue"
          placeholder="输入名称或条码"
          :prefix-icon="Search"
          style="max-width: 20vw"
          size="large"
      />
    </el-col>
  </el-row>
  <div v-if="radio==='新活动'">
    <el-table :data="tableData(search(curList))"
              height="68vh"
              style="width: 100%;"
    >
      <el-table-column label="商品名/条码" width="300">
        <template #default="scope">
          <el-row align='middle'>
            <el-col span="5">
              <el-image :src="scope.row.image" style="height: 70px;">
                <template #error>
                  <div class="image-slot">
                    <el-icon>
                      <Picture/>
                    </el-icon>
                  </div>
                </template>
              </el-image>
            </el-col>
            <el-col span="19" style="padding-left: 5%;">
              <el-row style="max-width: 145px">
                <el-text>{{ scope.row.goodsName }}</el-text>
              </el-row>
              <el-row>
                <el-text>{{ scope.row.code }}</el-text>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column prop="cost" label="成本价"/>
      <el-table-column prop="price" label="零售价"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button round type="warning" @click="showNewActivity(scope.row)">新活动</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div
        style="justify-content: center;align-items:center;height: 60px; background-color: rgba(255,255,255,0.72);boxShadow:1px 0px 1px #a6a6a6;z-index: 999;display: flex;padding: 5px 25px 5px 25px;">
      <div style="flex: 4;">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :background="true"
            layout="->,prev, pager, next, jumper"
            :total="search(curList).length"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  <div v-else>
    <el-table :data="tableData(offersList)"
              height="68vh"
              style="width: 100%;"
              :show-header="false"
              :cell-style="{ textAlign: 'center' }"
    >
      <el-table-column label="商品名/条码" width="300">
        <template #default="scope">
          <div v-if="scope.row.code!=='global'">
            <el-row align='middle' justify="center">
              <el-col span="5">
                <el-image :src="(store.getLocalStorage(scope.row.code)!==null)?(store.getLocalStorage(scope.row.code).image):('http://bt.golxen.com:15357/down/ijnXgaRVvBU5')" style="height: 70px;">
                  <template #error>
                    <div class="image-slot">
                      <el-icon>
                        <Picture/>
                      </el-icon>
                    </div>
                  </template>
                </el-image>
              </el-col>
              <el-col span="19" style="padding-left: 5%;">
                <el-row style="max-width: 145px">
                  <el-text>{{
                      store.getLocalStorage(scope.row.code) != null ? store.getLocalStorage(scope.row.code).goodsName : "已删除商品"
                    }}
                  </el-text>
                </el-row>
                <el-row>
                  <el-text>{{ scope.row.code }}</el-text>
                </el-row>
              </el-col>
            </el-row>
          </div>
          <div v-else>
            <el-text size="large" style="margin-left: 3%">全局活动</el-text>
          </div>
        </template>
      </el-table-column>
      <el-table-column>
        <template #default="scope">
          <div style="text-align: center">
            <div>{{getAttach(scope.row.attachObj).fullDecr}}</div>
            <div>{{getAttach(scope.row.attachObj).discount}}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column>
        <template #default="scope">
          <div style="text-align: center">
            <div>开始时间：{{scope.row.startDate}}</div>
            <div>结束时间：{{scope.row.endDate}}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button v-if="!isExpire(scope.row.endDate)" round type="danger" @click="showEndActivity(scope.row)">结束活动</el-button>
          <el-button v-else disabled round type="info" style="width: 90px;">已结束</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div
        style="justify-content: center;align-items:center;height: 60px; background-color: rgba(255,255,255,0.72);boxShadow:1px 0px 1px #a6a6a6;z-index: 999;display: flex;padding: 5px 25px 5px 25px;">
      <div style="flex: 4;">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :background="true"
            layout="->,prev, pager, next, jumper"
            :total="search(curList).length"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <el-dialog v-model="isAddActivity" title="新活动" width="30%" center>
    <el-form label-width="120px">
      <div>
        <div>
          打折:
          <el-switch v-model="isDiscount"/>
        </div>
        <div>
          <el-input-number size="small" :disabled="!isDiscount" v-model="storeOffersAttach.discount" :min="1" :max="9.9"
                           style="width: 80px"/>
          折
        </div>
      </div>
      <br/>
      <div>
        <div>
          满减:
          <el-switch v-model="isFullDecr"/>
        </div>
        <div>
          满
          <el-input-number size="small" :disabled="!isFullDecr" v-model="storeOffersAttach.fullDecr" :min="0"
                           style=" width: 100px"/>
          减
          <el-input-number size="small" :disabled="!isFullDecr" v-model="storeOffersAttach.fullDecrCost" :min="0"
                           :max="storeOffersAttach.fullDecr" style="width:100px "/>
        </div>
      </div>
      <br/>
      <div>
        <el-date-picker
            v-model="curPeriod"
            type="date"
            placeholder="结束日期"
            unlink-panels
            style="margin: 10px 0 0 10px"
            @change="changePeriod"
            :disabled="!isFullDecr&&!isDiscount"
            :disabled-date="disabledDateFun"
        />
      </div>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelAdd">取消</el-button>
        <el-button type="primary" @click="submitAdd">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  Search,
} from '@element-plus/icons-vue'
import {onMounted, ref} from "vue";
import {store} from "@/store";
import request from "@/utils/request";
import {dateTimeUtils} from "@/utils/dateTimeUtils";
import {ElMessage, ElMessageBox} from "element-plus";

const radio = ref("活动列表")
const typeList = ref([])
let curType = ref("全部商品")
let dataList = ref([])
let curList = ref([])
const searchValue = ref("")
const isRunning = ref(false)
const currentPage = ref(1)
const pageSize = ref(30)
let isAddActivity = ref(false)
// let addActivityTemp=ref({})
let goodsList = ref([])
let offersList = ref([])

let isFullDecr = ref(false)
let isDiscount = ref(false)
let storeOffersAttach = ref({})
let storeOffers = ref({
  storeId: store.getLocalCurrentStoreMain().storeId
})
const curPeriod = ref('')

onMounted(() => {
  request.get("/goods/get/goodsCodeList/" + store.getLocalCurrentStoreMain().storeId).then(res => {
    for (let i in res.data) {
      goodsList.value.push(store.getLocalStorage(res.data[i]))
    }
    for (let i in goodsList.value) {
      if (typeList.value.indexOf(goodsList.value[i].goodsType) === -1)
        typeList.value.push(goodsList.value[i].goodsType)
    }
    typeList.value.unshift("全部商品")
  })
  request.get("/store/get/StoreOffersListHistory/" + store.getLocalCurrentStoreMain().storeId).then(res => {
    offersList.value = res.data.sort(function (a, b) {
      return b.startDate.localeCompare(a.startDate)
    })
    dataList.value = offersList.value
  })
})
const filList = (key, list) => {
  if (key === "全部商品")
    key = ""
  // 返回过滤后的数组
  return list.filter((p) => {
    return p.goodsType.indexOf(key) !== -1
  })
}
const handleSelect = (key) => {
  curType.value = key
  curList.value = filList(key, dataList.value)
}
const search = (list) => {
  return list.filter((p) => {
    return p.goodsName.indexOf(searchValue.value) !== -1 || p.code.indexOf(searchValue.value) !== -1
  })
}
const handleCurrentChange = (e) => {
  currentPage.value = e;
};
const tableData = (list) => {
  return list.filter(
      (item, index) =>
          index < currentPage.value * pageSize.value &&
          index >= pageSize.value * (currentPage.value - 1)
  );
};
const updateRadio = () => {
  if (radio.value === "活动列表") {
    dataList.value = goodsList.value
    handleSelect(curType.value)
  } else {
    dataList.value = offersList.value
  }

}
const showNewActivity = (data) => {
  storeOffers.value.code = data.code
  isAddActivity.value = true
}
const changePeriod = () => {
  storeOffers.value.startDate = dateTimeUtils.getBusinessDateBo(new Date()).formatDateByDay
  storeOffers.value.endDate = dateTimeUtils.getBusinessDateBo(curPeriod.value.setDate(curPeriod.value.getDate() + 1)).formatDateByDay
}
const disabledDateFun = (time) => {
  // time 为new Date()类型
  return time.getTime() < new Date(dateTimeUtils.getBusinessDateBo(new Date()).formatDateByDay).getTime(); //时间范围必须是时间戳
}
const cancelAdd = () => {
  isFullDecr.value = false
  isDiscount.value = false
  storeOffersAttach.value = {}
  storeOffers.value = {
    storeId: store.getLocalCurrentStoreMain().storeId
  }
  curPeriod.value = ''
  isAddActivity.value = false
}
const submitAdd = () => {
  if (!isFullDecr.value && !isDiscount.value) {
    ElMessage({
      message: '至少选择一项策略',
      type: 'warning',
    })
    return;
  }
  if (storeOffers.value.startDate === undefined && storeOffers.value.endDate === undefined) {
    ElMessage({
      message: '请选择时间范围',
      type: 'warning',
    })
    return
  }
  storeOffersAttach.value.attach = ""
  if (isFullDecr.value) {
    if (isNaN(storeOffersAttach.value.fullDecr) || isNaN(storeOffersAttach.value.fullDecrCost)) {
      ElMessage({
        message: '检查优惠数值是否填写',
        type: 'warning',
      })
      return;
    } else
      storeOffersAttach.value.attach += "满减 "
  }

  if (isDiscount.value) {
    if (isNaN(storeOffersAttach.value.discount)) {
      ElMessage({
        message: '检查优惠数值是否填写',
        type: 'warning',
      })
      return;
    } else {
      storeOffersAttach.value.attach += "打折"
      storeOffersAttach.value.discount = (storeOffersAttach.value.discount / 10).toFixed(2)
    }
  }
  storeOffers.value.attachObj = storeOffersAttach.value
  request.post("/store/add/storeOffers", storeOffers.value).then(res => {
    if (res.code === 200) {
      cancelAdd()
      ElMessage({
        message: '新活动添加成功',
        type: 'success',
      })
      request.get("/store/get/StoreOffersListHistory/" + store.getLocalCurrentStoreMain().storeId).then(res => {
        offersList.value = res.data.sort(function (a, b) {
          return b.startDate.localeCompare(a.startDate)
        })
      })
    } else {
      ElMessage({
        message: res.message,
        type: 'warning',
      })
    }

  })
}
const runOrAll = () => {
  if (isRunning.value===true){
    request.get("/store/get/StoreOffersListRuing/" + store.getLocalCurrentStoreMain().storeId).then(res => {
      offersList.value = res.data.sort(function (a, b) {
        return b.startDate.localeCompare(a.startDate)
      })
    })
  }else {
    request.get("/store/get/StoreOffersListHistory/" + store.getLocalCurrentStoreMain().storeId).then(res => {
      offersList.value = res.data.sort(function (a, b) {
        return b.startDate.localeCompare(a.startDate)
      })
    })
  }
}
const isExpire = (data) => {
  return new Date()>=new Date(data)
}
const getAttach = (data) => {
  let fullDecr=""
  let discount=""
    if(data.attach.indexOf("满减")!==-1){
      fullDecr="满 "+data.fullDecr+" 减 "+data.fullDecrCost
    }
    if(data.attach.indexOf("打折")!==-1){
      discount="打 "+data.discount*10+" 折"
    }
    return {
      fullDecr,
      discount
    }
}
const showEndActivity = (data) => {
  ElMessageBox.confirm(
      '确定结束此活动吗?',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        request.get("/store/update/endStoreOffers/"+store.getLocalCurrentStoreMain().storeId+"/"+data.code).then(res=>{
          runOrAll()
          ElMessage({
            message: "活动已结束",
            type: 'success',
          })
        })
      })

}
</script>

<style scoped>

</style>